<?php

namespace app\api\controller;

use app\common\controller\Api;
use think\Db;

/**
 * 登录接口
 */
class Login extends Api
{

    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];
    // 获取换取 openId, sessionKey, unionId
    public function openid(){
        $arrContextOptions=array(
            "ssl"=>array(
                "verify_peer"=>false,
                "verify_peer_name"=>false,
            ),
        );
        $code = $this->request->get('code');
        $appId = 'wx16ec9d917643887c';
        $Secret = '7e37d72735b88a5bd656a0f825bf6662';
        $url = "https://api.weixin.qq.com/sns/jscode2session?appid=".$appId."&secret=".$Secret."&js_code=".$code."&grant_type=authorization_code";
        $weixin = file_get_contents($url, false, stream_context_create($arrContextOptions));
        $jsondecode = json_decode($weixin); //对JSON格式的字符串进行编码
        $array = get_object_vars($jsondecode);//转换成数组
        return json_encode($array);
    }
    // 解密数据
    public function decrypt(){
        require_once VENDOR_PATH . 'decryption/wxBizDataCrypt.php';
        $appid = 'wxcb8cf13690d4d9c8';
        $sessionKey = $this->request->get('session_key');
        $encryptedData = $this->request->get('encryptedData');
        $iv = $this->request->get('iv');
        $pc = new \WXBizDataCrypt($appid, $sessionKey);
        $errCode = $pc->decryptData($encryptedData, $iv, $data);
        if ($errCode == 0) {
            return $data;
        } else {
            return $errCode;
        }
    }
    //存储用户信息
    public function user(){
        $data = array();
        $data['openid'] = $this->request->get('openid');
        $data['image'] = $this->request->get('img');
        $data['name'] = $this->request->get('name');
        $data['student_id'] = $this->request->get('student_id');
        $data['createtime'] = time();
        $file = ROOT_PATH."test.txt";
        $content = "时间： ".date("Y-m-d H:i:s",time())."\r\n"."\r\n\r\n\r\n"."student_id : ".$data['student_id'];
        file_put_contents($file, $content,FILE_APPEND);
        $status = Db::name('student')->where('openid',$data['openid'])->find();
        if($status == 0){
            //第一次获取用户信息
            $res = Db::name('student')->insert($data);
        }else{
            //已经存在此用户信息
            $res = Db::name('student')->where('openid',$data['openid'])->update(['name' =>$data['name'],'image'=>$data['image']]);
        }
        return $res?200:400;
    }
}
